﻿/*
 *  spells.js
 *
 *  A jQuery plugin to handle changes to the character known spells list.
 */
 (function ($) {
     var settings = {
         updateSpellUrl: '',
         spellUpdatedCallback: null,
         spellUpdatedErrorCallback: null,
         refreshSpellsUrl: '',
         spellsContainer: '.spells-container',
         spellsCallback: null,
         knownSpellLimits: null,
         schoolsUrl: '',
         schoolsContainerSelector: '',
         schoolsRefreshedCallback: null
     };

     var methods = {
         init: function (options) {
             settings = $.extend(settings, options);

             bindSpells();
         },
         refreshSchools: function (content) {
             _refreshSchools();
         },
         refreshSpells: function (content) {
             _refreshSpells();
         }
     };


     $.fn.spells = function (method) {

         // Method calling logic
         if (methods[method]) {
             return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
         } else if (typeof method === 'object' || !method) {
             return methods.init.apply(this, arguments);
         } else {
             $.error('Method ' + method + ' does not exist on spells object.');
         }

     };

     function bindSpells() {
         // bind the knwon spell check box to detect when any selection changes.
         $('input.spell-selected, input.spell-attuned', settings.spellsContainer).each(function () {
             $(this).change(function () {
                 // get row parent and spell group name.
                 var parent = $(this).parents('tr[data-group-name]')[0];

                 if (!parent)
                     return; // do nothing.

                 updateSpell(parent);
             });
         });
     }

     function updateSpell(parent) {
         var $parent = $(parent);
         var spellGroup = $parent.attr('data-group-name');

         // get selected value.
         var selectedElement = $parent.find('input.spell-selected')[0];

         if (!selectedElement)
             return;

         var selected = $(selectedElement).is(':checked');

         // get attuned click.
         var attunedElement = $parent.find('input.spell-attuned')[0];

         if (!attunedElement)
             return;

         var attuned = $(attunedElement).is(':checked');

         if (!validateSpellChoice($parent, spellGroup, selected, attuned)) {
             // if attuned checked uncheck it.
             if (attuned)
                 $(attunedElement).attr('checked', false);
             else if (selected)
                 $(selectedElement).attr('checked', false);

             return;
         }

         var url = settings.updateSpellUrl + '?group=' + spellGroup + '&selected=' + selected + '&attuned=' + attuned;

         doAjaxGet(url,
            settings.spellsContainer,
            function () {
                if (settings.spellUpdatedCallback)
                    settings.spellUpdatedCallback();

                bindSpells(); // ensure these events are re bound to new html elements.

                showMessage('Spell ' + spellGroup + ' updated.');
            },
            function (data) {
                showErrorText('Failed to update spell ' + spellGroup + '.');
                showWarning(data);

                if (spellUpdatedErrorCallback)
                    spellUpdatedErrorCallback();
            },
            false
        );
     }

     // Validate that the spell choice is valid.
     function validateSpellChoice(parent, spellGroup, selected, attuned) {
         if (!selected || !settings.knownSpellLimits)
             return true; // un-selecting or no limits is always a valid action.

         // get spell colour andtype from parent
         //var spellColour = parent.attr('data-colour');
         var spellType = parent.attr('data-type');

         // get sum of all spells selected or attuned within this colour.
         var sumChecked = 0;

         sumChecked = parent.parent().find("tr[data-is-system='false'][data-type='" + spellType + "'] input[type=checkbox]:checked").length;

         // get allowed for this colour
         var allowedSpells = eval('settings.knownSpellLimits.' + spellType);

         var valid = (allowedSpells >= sumChecked);

         if (!valid)
             showMessage('Insufficient known spells available.  Spend more status on learn spells skills to know more spells.');

         return valid;
     }

     function _refreshSchools() {
         // reload the header container content via ajax.
         doAjaxGet(
                settings.schoolsUrl,
                settings.schoolsContainerSelector,
                function () {
                    // refresh jquery event binding.
                    //bindHeaderEvents();

                    if (settings.schoolsRefreshedCallback)
                        settings.schoolsRefreshedCallback();
                },
                showWarning);
     }

     function _refreshSpells() {
         // reload the header container content via ajax.
         doAjaxGet(
                settings.refreshSpellsUrl,
                settings.spellsContainer,
                function () {
                    // refresh jquery event binding.
                    bindSpells();

                    if (settings.spellsCallback)
                        settings.spellsCallback();
                },
                showWarning);
     }

 })(jQuery);